import * as $member from '@/api/member'

export const MEMBER_SET_MEMBERS = 'MEMBER_SET_MEMBERS'
export const MEMBER_TOGGLE_CHECK = 'MEMBER_TOGGLE_CHECK'
export const MEMBER_SET_CHECK_ALL = 'MEMBER_SET_CHECK_ALL'

const state = () => {
  return {
    members: []
  }
}

const getters = {
  members (state) {
    let members = state.members
    for (let i = 0; i < members.length; i++) {
      if (members[i].checked === 'undefined') {
        members[i].checked = false
      }
    }
    return members
  }
}

const actions = {
  async getSubmitedsByTaskId ({ commit, state, rootState }, taskId) {
    let members = await $member.getSubmitedsByTaskId(taskId)
    commit(MEMBER_SET_MEMBERS, members)
    return members
  },
  toggleCheck ({ commit, state, rootState }, idx) {
    commit(MEMBER_TOGGLE_CHECK, idx)
  },
  setCheckAll ({ commit, state, rootState }, value) {
    commit(MEMBER_SET_CHECK_ALL, value)
  },
}

const mutations = {
  MEMBER_SET_MEMBERS (state, members) {
    state.members = members
  },
  MEMBER_TOGGLE_CHECK (state, idx) {
    if (!state.members[idx]) return
    let t = []
    state.members.forEach((n, i) => {
      if (i === idx) {
        n.checked = !n.checked
      }
      t.push(n)
    })
    state.members = t
  },
  MEMBER_SET_CHECK_ALL (state, value) {
    let t = []
    state.members.forEach((n, i) => {
      n.checked = value
      t.push(n)
    })
    state.members = t
  },
}

export default {
  namespaced: true,
  state,
  getters,
  actions,
  mutations
}
